import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtList, AtListItem, AtGrid, AtButton, AtActionSheet, AtActionSheetItem, AtTabBar } from 'taro-ui'
// import { AtActionSheet, AtActionSheetItem } from "taro-ui"
import './dongtaishouye.scss'
import { $navigateTo, $redirectTo, getGlobalData } from '../../../../global';
// import reactMixin from 'react-mixin';
import myJs from './dongtaishouyeJs.js'
import app from '../../../../main.js'

export default class Dongtaishouye extends Component {
    config = {
        navigationBarTitleText: '动态首页'
    }
    constructor() {
        super(...arguments);
        this.state = {
            topicss: {
                items: []
            },
            articless: {
                offset: 0,
                length: 25,
                items: [{
                    id: '',
                    title: '',
                    image: '',
                    url: '',
                }]
            },
            dongtaiss: [],
            video: [],
            tbar_current: 1
        };
    }

    handleChange(name, v) {
        console.log("handleChange触发")
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }
        temp[names[i]] = v;
        this.setState({n: temp[names[i]]});
    }
    handleTextareaChange(name, e) {
        console.log("handleTextareaChange")
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }
        temp[names[i]] = e.target.value;
        this.setState({n: temp[names[i]]});
    }
    handleClick(value) {
        console.log("handleClick")
        this.setState({
            tbar_current: value
        });
        if (value == 0) {
            app.redirectTo('../../../doctorpages/homepage/homepage');
        }
        if (value == 2) {
            app.redirectTo('../../../center/pages/personalcenter/personalcenter');
        }
    }
    // 上拉加载
    offset = 0;
    length = 9;
    onReachBottom() {
        // 分页逻辑,下拉到底部触发时间
        if (this.state.total > this.offset) {
            Taro.showToast({
                title:'正在加载...',
                icon:'success',
                duration: 3000
            })
                this.offset = this.offset + this.length;
                this.getDongtaiss();
        }else{
            app.toast('没有更多了')
        }
    }
    //跳转消息
    newsHomepage = () => {
        app.redirectTo('../newshomepage/newshomepage');
    }
    //跳转个人中心
    personalCenter = () => {
        app.redirectTo('../../../center/pages/personalcenter/personalcenter');
    }
    //跳转首页
    homePage = () => {
        app.redirectTo('../../../doctorpages/homepage/homepage');
    }
    // 跳转动态详情
    go(url) {
        // app.navigateTo(url);
        app.navigateTo(url)
    }
    // 跳转病历详情
    go2(content) {
    
        console.log("超连接跳转执行",content)
        let url = content.substring(content.indexOf('病历链接')+4,content.indexOf(':'))
        console.log(content.indexOf(':'))
        console.log("newurk",url)
        app.navigateTo('/pages/doctorpages/caseDetail/caseDetail?id='+url)
    }
    //底部弹框
    selectedType() {
        var isOpen = true;
        this.setState({
            isOpen: isOpen
        });
    }
    // 发布动态按钮
    publish(type) {
        var url = '../fabudongtai/fabudongtai?type=' + type;
        var isOpen = this.state.isOpen;
        isOpen = false;
        this.setState({
            isOpen: isOpen
        });
        app.navigateTo(url);
    }

    //视频上传 返回临路径
    chooseVideo(type) {
        var that = this;
        var isOpen = that.state.isOpen;
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            camera: 'back',
            success(res) {
                var tmp = res.tempFilePath;
                app.navigateTo('../fabudongtai/fabudongtai?type=' + type + '&video=' + tmp);
            }
        })

        isOpen = false;
        that.setState({
            isOpen: isOpen
        });
    }
    // 点赞
    clickFavour(chat_id, index, item, num) {
        console.log(index, num)
        if (num == 0) {
            var me = this;
            var dongtaiss = me.state.dongtaiss;
            app.post("web/dynamic_topic/likeDynamic", { chat_id: chat_id }, function (res) {
                var like = res.data.result;
                if (dongtaiss[index].id = chat_id) {
                    if (like.is_like == '已点赞') {
                        dongtaiss[index].likeNum += 1;
                        dongtaiss[index].is_like = '已点赞'
                    } else {
                        dongtaiss[index].likeNum -= 1;
                        dongtaiss[index].is_like = '未点赞'
                    }
                }
                me.setState({
                    dongtaiss: dongtaiss
                })
            });
        }
        if (num == 1) {
            var me = this;
            var dongtaiss = me.state.dongtaiss;
            app.post("web/dynamic_topic/collectDynamic", { chat_id: chat_id }, function (res) {
                var collect = res.data.result;
                if (dongtaiss[index].id = chat_id) {
                    if (collect.is_collect == '已收藏') {
                        dongtaiss[index].collectNum += 1;
                        dongtaiss[index].is_collect = '已收藏'
                    } else {
                        dongtaiss[index].collectNum -= 1;
                        dongtaiss[index].is_collect = '未收藏'
                    }
                }
                me.setState({
                    dongtaiss: dongtaiss
                })
            });
        }
        if (num == 2) {
            $navigateTo('../dongtaixiangqing/dongtaixiangqing?chat_id=' + chat_id);
        }
        if (num == 3) {
            $navigateTo('../dongtaixiangqing/dongtaixiangqing?chat_id=' + chat_id);
        }
    }
    like(topic_id, index, e) {
        e.stopPropagation();
        var me = this;
        var topicss = me.state.topicss;
        app.post("web/dynamic_topic/likeTopic", { topic_id: topic_id }, function (res) {
            var like = res.data.result;
            if (topicss.items[index].id == topic_id) {
                if (topicss.items[index].id == topic_id) {
                    if (like.is_like == '已点赞') {
                        topicss.items[index].likeNum += 1;
                        topicss.items[index].is_like = '已点赞'
                    } else {
                        topicss.items[index].likeNum -= 1;
                        topicss.items[index].is_like = '未点赞'
                    }
                }
            }
            me.setState({
                topicss: topicss
            })
        });
    }
    no(e) {
        e.stopPropagation();
    }
    // 数据获取 话题列表
    getTopics() {
        var me = this;
        app.get('web/dynamic_topic/topicList', {offset: 0, length: 3}, function(res) {
            var topicss = me.state.topicss;
            topicss.items = res.data.result.list;
            me.setState({
                topicss: topicss
            });
        });
    }
    // 获取动态数据
    getDongtaiss() {
        var me = this;
        let list = [];
        app.get('web/dynamic_topic/dynamicList', {offset: me.offset, length: me.length}, function(res) {
            list  = me.state.dongtaiss.concat(res.data.result.list)
            me.setState({
                total: res.data.result.total,
                dongtaiss: list
            });
        });
    }
    getDongtais() {
        var me = this;
        let list = [];
        app.get('web/dynamic_topic/dynamicList', {offset: 0, length: 25}, function(res) {
            list  = res.data.result.list
            me.setState({
                total: res.data.result.total,
                dongtaiss: list
            });
        });
    }
    
    init() {
      
        // this.getDongtaiss();
    }
    componentWillMount(){
        console.log("有没有blurl",this.$router.params.blurl)
        console.log('token',app.getToken())
        this.init()
    }
    componentDidMount () {
    }
    
    componentDidShow () {
        this.getTopics();
        this.getDongtais()
    }
    componentWillUnmount () {
    }
    componentDidHide () {}

    render() {
        // 本地图片
        let dianzan = app.imageUri + 'img/icon-dianzan.png'
        let nodianzan = app.imageUri + 'img/icon-dianzan-kong.png'
        let shoucan = app.imageUri + 'img/icon-shoucan-man.png'
        let noshoucan = app.imageUri + 'img/icon-shoucan-kong.png'

       

        return (
            <View className='dongtaishouye'>
                <View className=' class_0'>
                    {
                        this.state.topicss.items.map((item, index) => {
                            return (
                                <View key={index} className=' class_1' onClick={this.go.bind(this, '../huati/huati?id=' + item.id)}>
                                    <View className=' class_2'>
                                        <Text className=' class_3'>{item.title}</Text>
                                        <View className=' class_4'>
                                            <View className=' class_5'>
                                                <Image mode='widthFix' className=' class_6' src={item.is_like == '已点赞' ? dianzan : nodianzan} onClick={this.like.bind(this, item.id, index)}></Image>
                                                <Text className=' class_7'>{item.likeNum}</Text>
                                            </View>
                                            <View className=' class_8'>
                                                <Image className=' class_9' src={app.imageUri + 'img/icon-comment-kong.png'}></Image>
                                                <Text className=' class_10'>{item.commentNum}</Text>
                                            </View>
                                        </View>
                                    </View>
                                    <View>
                                        <Image className=' class_11' src={app.getPath(item.image)}></Image>
                                    </View>
                                </View>
                            );
                        })
                    }
                </View>
                <AtButton onClick={this.go.bind(this, '../wangqihuati/wangqihuati')}><Text className='more-text'>更多</Text></AtButton>
                    {/* 动态列表 */}
                <View>
                    {
                        this.state.dongtaiss.map((items, index,arr) => {
                            return (
                                <View className='class_37' key={items.id}>
                                    <AtList>
                                        <AtListItem hasBorder={false} title={items.name} note={items.hospital} extraText={items.created_at} thumb={app.getPath(items.head_image)} onClick={this.go.bind(this, '../doctorhomepage/doctorhomepage?doctor_id=' + items.member_id)}></AtListItem>
                                    </AtList>   
                                    <View className='class_38'>
                                        <View className='at-article '>  
                                            {items.content_type =='病历'
                                                ?( items.media_type == '文本' | items.media_type == '图片'
                                                ?  <View className='at-article__p class_39' onClick={this.go2.bind(this, items.content)} ><Text className='at-article__p class_391'>病历链接</Text><Text>{items.content.indexOf('病历链接') == 0 ? items.content.substring(items.content.indexOf(':')+1,items.content.length) : items.content}</Text></View>
                                                : <View className='at-article__p class_39' onClick={this.go.bind(this, '../dongtaixiangqing/dongtaixiangqing?chat_id=' + items.id)}>{items.content}</View>
                                                )
                                                : <View className='at-article__p class_39' onClick={this.go.bind(this, '../dongtaixiangqing/dongtaixiangqing?chat_id=' + items.id)}>{items.content}</View>
                                            }
                                        </View>
                                        {items.media_type == '图片' ?
                                            <View className=' class_40' onClick={this.go.bind(this, '../dongtaixiangqing/dongtaixiangqing?chat_id=' + items.id)}>
                                                {
                                                    items.images.map((item, index) => {
                                                        return (
                                                            <Image key={index} mode className='class_41' src={item}></Image>
                                                        );
                                                    })
                                                }
                                            </View>
                                            : items.media_type == '视频' ?
                                                <View className='class_40'>
                                                    {
                                                        items.images.map((item, index) => {
                                                            return (
                                                                <video controls={true} initial-time='0.01' src={item}></video>
                                                            );
                                                        })
                                                    }
                                                </View>
                                                : <View></View>
                                        }
                                    </View>
                                    {/* 动态按钮 */}
                                    <AtGrid mode='rect' className='fun-box' onClick={this.clickFavour.bind(this, items.id, index)} hasBorder={false} columnNum={4} data={[
                                        { image: items.is_like == '已点赞' ? dianzan : nodianzan, value: items.likeNum },
                                        { image: items.is_collect == '已收藏' ? shoucan : noshoucan, value: items.collectNum },
                                        { image: app.imageUri + 'img/icon-comment-kong.png', value: items.commentNum },
                                        { image: app.imageUri + 'img/icon-zhuangfa.png', value: items.transpondNum }]}>
                                    </AtGrid>
                                </View>
                            )
                        })
                    }
                </View>
                <View className='blank-box'></View>
                <View className='footer at-row'>
                    <AtTabBar
                        fixed
                        tabList={[
                            { title: '首页', iconType: 'home' },
                            { title: '动态', iconType: 'message' },
                            { title: '我的', iconType: 'user' }
                        ]}
                        onClick={this.handleClick.bind(this)}
                        current={this.state.tbar_current}
                    />
                </View>

                <AtActionSheet isOpened={this.state.isOpen} cancelText='取消'>
                    <AtActionSheetItem onClick={this.publish.bind(this, '图片')}>
                        选择图片
                        </AtActionSheetItem>
                    <AtActionSheetItem onClick={this.chooseVideo.bind(this, '视频')}>
                        选择视频
                        </AtActionSheetItem>
                </AtActionSheet>

                <Image className='add-img' onClick={this.selectedType.bind(this)} src={app.imageUri + 'img/tianjiabingli.png'}></Image>

            </View>
        );
    }
}
// reactMixin.onClass(Dongtaishouye, myJs);